export default class Decoractor {
  static methodCdMap = {}; // 创建一个Map的数据结构，将实例化对象作为key

  static classEventMap = {}; //事件与函数的映射关系统

  /**
   * 函数调用装饰器，在CD时间内函数只能调用一次，防止频繁调用
   * @param {number} cd cd 单位为秒
   * @param {string} msg 频繁操作时的提示信息
   */
  static callLimit(cd: number = 1, msg: string = '') {
    return function (target, key, descriptor) {
      let oldValue = descriptor.value;
      descriptor.value = function () {
        let methodKey = target.__class__ + '_' + key;
        let lastCallTime = Decoractor.methodCdMap[methodKey] || 0;
        let current = new Date().getTime();
        if (current - lastCallTime > cd * 1000) {
          oldValue.apply(this, arguments);
          Decoractor.methodCdMap[methodKey] = current;
        } else {
          //msg && UIFacade.showToast(msg);
        }
      };
    };
  }

  /**
   * 事件装饰器
   * BattleView:
   *  battleReady: (2) ["onBattleStart", "onBattleEnd"]  会是这么个格式 BattleView是对象的className battleReady是事件key  数组里得事 BattleView里的响应方法
   *
   */
  static event(...eventNames) {
    return function (target, key, descriptor) {
      setTimeout(() => {
        let className = target.__classname__;
        let eventMethodmap = Decoractor.classEventMap[className];
        if (!eventMethodmap) {
          eventMethodmap = {};
        }
        eventNames.forEach((eventName) => {
          if (!eventMethodmap[eventName]) eventMethodmap[eventName] = [];
          if (eventMethodmap[eventName].indexOf(key) == -1) {
            eventMethodmap[eventName].push(key);
          }
        });
        Decoractor.classEventMap[className] = eventMethodmap;
      }, 0);
    };
  }
}
